package com.wshl.aijiuunion.controller.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.stx.xhb.xbanner.XBanner;
import com.wshl.aijiuunion.GlobConstant;
import com.wshl.aijiuunion.NetUrl;
import com.wshl.aijiuunion.R;
import com.wshl.aijiuunion.callback.RequestCallback;
import com.wshl.aijiuunion.controller.activity.VideoDetailActivity;
import com.wshl.aijiuunion.controller.activity.VideoSelectActivity;
import com.wshl.aijiuunion.controller.activity.WebActivity;
import com.wshl.aijiuunion.model.RequestModel;
import com.wshl.aijiuunion.utils.BarUtils;
import com.wshl.aijiuunion.utils.GlideUtils;
import com.wshl.aijiuunion.view.adapter.VideoListAdapter;
import com.wshl.aijiuunion.view.bean.Bannerbean;
import com.wshl.aijiuunion.view.bean.EventBeans;
import com.wshl.aijiuunion.view.bean.VideoIndexBean;
import com.wshl.aijiuunion.view.bean.VideoListBean;
import com.wshl.aijiuunion.view.widget.RoundCornerImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created buy 风凊扬 on 2019/10/21 0021
 */
public class VideoFragment extends TabFragment implements OnRefreshLoadMoreListener {
    @BindView(R.id.img_select)
    ImageView imgSelect;
    @BindView(R.id.video_xbanner)
    XBanner xbanner;
    @BindView(R.id.tv_live_title)
    TextView tvLiveTitle;
    @BindView(R.id.live_img)
    RoundCornerImageView liveImg;
    @BindView(R.id.tv_play_count)
    TextView tvPlayCount;
    @BindView(R.id.rl_live_img)
    RelativeLayout rlLiveImg;
    @BindView(R.id.tv_play_time)
    TextView tvPlayTime;
    @BindView(R.id.tv_live_yuyue)
    TextView tvLiveYuyue;
    @BindView(R.id.rl_live)
    RelativeLayout rlLive;
    @BindView(R.id.img_video1)
    RoundCornerImageView imgVideo1;
    @BindView(R.id.tv_video_title1)
    TextView tvVideoTitle1;
    @BindView(R.id.tv_video_play_count1)
    TextView tvVideoPlayCount1;
    @BindView(R.id.tv_video_time1)
    TextView tvVideoTime1;
    @BindView(R.id.img_video2)
    RoundCornerImageView imgVideo2;
    @BindView(R.id.tv_video_title2)
    TextView tvVideoTitle2;
    @BindView(R.id.tv_video_play_count2)
    TextView tvVideoPlayCount2;
    @BindView(R.id.tv_video_time2)
    TextView tvVideoTime2;
    @BindView(R.id.recycle_video)
    RecyclerView recycleVideo;
    @BindView(R.id.rl_new1)
    RelativeLayout rlNew1;
    @BindView(R.id.rl_new2)
    RelativeLayout rlNew2;
    @BindView(R.id.ll_new_kehceng)
    LinearLayout llNewKehceng;
    @BindView(R.id.refresh_video)
    SmartRefreshLayout refreshVideo;
    @BindView(R.id.tv_nocontent)
    TextView tvNocontent;
    private int type = 0;
    private int cateid = 0;
    private int page = 1;
    private VideoListAdapter adapter;

    @Override
    public void initImmersionBar() {
        BarUtils.setWhiteStatusBarForFragment(this);
    }


    private RequestModel model;
    private List<VideoListBean.DataBeanX.DataBean> listdata;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LogUtils.i("videofragment--oncreate");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_video, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        return view;


    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        model = new RequestModel();
        recycleVideo.setLayoutManager(new LinearLayoutManager(mContext));
        refreshVideo.setOnRefreshLoadMoreListener(this);
        getVideoData();
        getVIdeoList(false);

    }

    private void getVIdeoList(boolean isLoadmore) {
        model.videoList(mContext, type, cateid, page, new RequestCallback() {
            @Override
            public void onSuccess(String response) {

                VideoListBean videoListBean = GsonUtils.fromJson(response, VideoListBean.class);
                VideoListBean.DataBeanX data = videoListBean.getData();
                List<VideoListBean.DataBeanX.DataBean> data1 = data.getData();

                if (isLoadmore) {
                    refreshVideo.finishLoadMore();
                } else {
                    refreshVideo.finishRefresh();
                }
                if (adapter == null) {
                    listdata = new ArrayList<>();
                    listdata.addAll(data1);
                    if (listdata.size() == 0) {

                        tvNocontent.setVisibility(View.VISIBLE);
                        recycleVideo.setVisibility(View.GONE);
                        return;
                    }


                    tvNocontent.setVisibility(View.GONE);
                    recycleVideo.setVisibility(View.VISIBLE);
                    adapter = new VideoListAdapter(recycleVideo);
                    adapter.setData(listdata);
                    recycleVideo.setAdapter(adapter);

                } else if (isLoadmore) {

                    listdata.addAll(data1);
                    adapter.notifyDataSetChanged();

                } else {
                    listdata.clear();
                    listdata.addAll(data1);
                    if (listdata.size() == 0) {
                        tvNocontent.setVisibility(View.VISIBLE);
                        recycleVideo.setVisibility(View.GONE);
                    }else{
                        tvNocontent.setVisibility(View.GONE);
                        recycleVideo.setVisibility(View.VISIBLE);
                    }

                    adapter.notifyDataSetChanged();
                }


            }

            @Override
            public void onError(int code) {
                if (isLoadmore) {
                    refreshVideo.finishLoadMore();
                } else {
                    refreshVideo.finishRefresh();
                }
            }

            @Override
            public void onIntentError() {

            }
        });
    }

    private void getVideoData() {
        model.videoIndex(mContext, new RequestCallback() {
            @Override
            public void onSuccess(String response) {

                VideoIndexBean videoIndexBean = GsonUtils.fromJson(response, VideoIndexBean.class);
                VideoIndexBean.DataBean data = videoIndexBean.getData();
                List<VideoIndexBean.DataBean.BannerBean> banner = data.getBanner();
                List<VideoIndexBean.DataBean.ListBean> list = data.getList();
                if (banner != null && banner.size() > 0) {
                    setBanner(banner);
                }
                if (list != null && list.size() > 0) {

                    if (list.size() < 2) {
                        rlNew2.setVisibility(View.INVISIBLE);
                        showvideo(list);

                    } else if (list.size() >= 2) {
                        rlNew2.setVisibility(View.VISIBLE);
                        showvideo(list);
                        showvideo2(list);
                    }

                }


            }

            @Override
            public void onError(int code) {

            }

            @Override
            public void onIntentError() {

            }
        });
    }

    private void showvideo(List<VideoIndexBean.DataBean.ListBean> list) {
        VideoIndexBean.DataBean.ListBean listBean = list.get(0);
        String cover = listBean.getCover();
        String title = listBean.getTitle();
        String created_at = listBean.getCreated_at();
        int hits = listBean.getHits();

        GlideUtils.loadImage(mContext, NetUrl.IMG + cover, imgVideo1);
        tvVideoTitle1.setText(title);
        tvVideoPlayCount1.setText(hits + "次观看");
        tvVideoTime1.setText(created_at.substring(0,10));

        List<String> types = listBean.getType();
        String type_name = listBean.getType_name();

        rlNew1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String type = SPUtils.getInstance().getString(GlobConstant.TYPE, "0");
                if (!type_name.equals("全部") && !types.contains(type)) {
                    ToastUtils.showLong("您当前身份不能学习此课程");
                    return;
                }
                Intent intent = new Intent(mContext, VideoDetailActivity.class);
                intent.putExtra(GlobConstant.VIDEOID, listBean.getId());
                ActivityUtils.startActivity(intent);
            }
        });
    }

    private void showvideo2(List<VideoIndexBean.DataBean.ListBean> list) {
        VideoIndexBean.DataBean.ListBean listBean = list.get(1);
        String cover = listBean.getCover();
        String title = listBean.getTitle();
        String created_at = listBean.getCreated_at();
        int hits = listBean.getHits();

        GlideUtils.loadImage(mContext, NetUrl.IMG + cover, imgVideo2);
        tvVideoTitle2.setText(title);
        tvVideoPlayCount2.setText(hits + "次观看");
        tvVideoTime2.setText(created_at.substring(0,10));

        List<String> types = listBean.getType();
        String type_name = listBean.getType_name();

        rlNew2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String type = SPUtils.getInstance().getString(GlobConstant.TYPE, "0");
                if (!type_name.equals("全部") && !types.contains(type)) {
                    ToastUtils.showLong("您当前身份不能学习此课程");
                    return;
                }
                Intent intent = new Intent(mContext, VideoDetailActivity.class);
                intent.putExtra(GlobConstant.VIDEOID, listBean.getId());
                ActivityUtils.startActivity(intent);
            }
        });
    }

    private void setBanner(final List<VideoIndexBean.DataBean.BannerBean> bannerdata) {

        final List<String> imageUrls = new ArrayList<>();
        List<Bannerbean> banners = new ArrayList<>();
        for (VideoIndexBean.DataBean.BannerBean bannerdatum : bannerdata) {
            banners.add(new Bannerbean(NetUrl.IMG + bannerdatum.getCover()));
            imageUrls.add(NetUrl.IMG + bannerdatum.getCover());
        }

        xbanner.setBannerData(banners);
        xbanner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                GlideUtils.loadImage(mContext, ((Bannerbean) model).getXBannerUrl(), (ImageView) view);

            }
        });
        xbanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, Object model, View view, int position) {

                Intent intent = new Intent(mContext, WebActivity.class);
                intent.putExtra(GlobConstant.WEBURL, bannerdata.get(position).getLinkurl());
                startActivity(intent);
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            LogUtils.i("videofragment--页面显示");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }


    @OnClick(R.id.img_select)
    public void onViewClicked() {

        Intent intent = new Intent(mContext, VideoSelectActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("cateid", cateid);
        ActivityUtils.startActivityForResult(mContext, intent, 103);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getdata(EventBeans eventBeans) {


        String code = eventBeans.getCode();
        if (code.equals(GlobConstant.VIDEOSELECT)) {

            type = eventBeans.getType();
            cateid = eventBeans.getCateid();
            LogUtils.i("type:" + type);
            LogUtils.i("cateid:" + cateid);
            page = 1;
            getVIdeoList(false);
        }


    }


    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        getVIdeoList(true);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        page = 1;

        getVIdeoList(false);
        getVideoData();
    }
}
